import React, { useState } from 'react';
import { Tooltip } from 'antd';
import CodeBlock from './CodeBlock';
import { Components, ExtraProps } from 'react-markdown';
import { DetailedHTMLProps, HTMLAttributes } from 'react';
import { isBase64 } from '@/utils/common';

interface MarkdownComponentsProps {
  handleSend: (message: string) => void;
  setDefaultCollectionId: (collectionId: string) => void;
}

type MarkdownComponentProps = DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> & ExtraProps & {
  'data-tooltip'?: string;
  'data-link'?: string;
  'data-header'?: string;
  'data-ts'?: string;
  'collection-id'?: string;
  inline?: boolean;
  href?: string;
  src?: string;
  alt?: string;
};

export const createMarkdownComponents = ({ handleSend, setDefaultCollectionId }: MarkdownComponentsProps): Components => ({
  code: React.forwardRef<HTMLElement, MarkdownComponentProps>((props, ref) => {
    const { node, inline, className, children, ...rest } = props;
    const match = /language-(\w+)/.exec(className || '');
    return !inline && match ? (
      <CodeBlock language={match[1]} code={String(children).replace(/\n$/, '')} />
    ) : (
      <code ref={ref} className={className} {...rest}>
        {children}
      </code>
    );
  }),

  img: React.forwardRef<HTMLImageElement, MarkdownComponentProps>((props, ref) => {
    const { node, src, alt, ...rest } = props;
  
    // 如果是 base64 图片但没有 data: 前缀，添加前缀
    let imageSrc = src;
    if (src && isBase64(src) && !src.startsWith('data:image/')) {
      imageSrc = `data:image/png;base64,${src}`;
    }
    
    return (
      <img
        ref={ref}
        src={imageSrc}
        alt={alt || ''}
        style={{
          maxWidth: '100%',
          height: 'auto',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
        }}
        {...rest}
      />
    );
  }),

  a: React.forwardRef<HTMLAnchorElement, MarkdownComponentProps>((props, ref) => {
    const { node, href, children, ...rest } = props;
    const linkText = Array.isArray(children) ? children[0] : children;

    const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
      if (!href || href === '#' || href === '') {
        e.preventDefault();
        e.stopPropagation();
        if (typeof linkText === 'string') {
          handleSend(linkText);
        }
      } else {
        e.preventDefault();
        window.open(href, '_blank');
      }
    };

    return (
      <a
        ref={ref}
        {...rest}
        href="#"
        onClick={handleClick}
        style={{ cursor: 'pointer', color: '#1890ff' }}
      >
        {children}
      </a>
    );
  }),

  table: React.forwardRef<HTMLTableElement, MarkdownComponentProps>((props, ref) => {
    const { node, children, ...rest } = props;
    return (
      <table ref={ref} {...rest} style={{ color: 'black' }}>
        {children}
      </table>
    );
  }),

  span: React.forwardRef<HTMLSpanElement, MarkdownComponentProps>((props, ref) => {
    const { node, className, children, ...rest } = props;
    if (className === 'eaitip' && rest['data-tooltip']) {
      const tooltip = rest['data-tooltip'] || '';
      const link = rest['data-link'] || '';
      const header = rest['data-header'] || '';
      const ts = rest['data-ts'] || '';
      const collectionId = rest['collection-id'] || '';

      const [isHovered, setIsHovered] = useState(false);

      const handleClick = () => {
        if (link) {
          window.open(link, '_blank');
        } else if (collectionId) {
          setDefaultCollectionId(collectionId);
        }
      };

      const tooltipContent = (
        <div>
          {header && (
            <div
              style={{
                color: '#474C5F',
                fontWeight: 600,
                fontSize: '14px',
                padding: '4px 8px',
              }}
            >
              {header}
            </div>
          )}
          {ts && (
            <div
              style={{
                color: '#474C5F99',
                fontWeight: 300,
                fontSize: '12px',
                padding: '2px 8px',
              }}
            >
              {ts}
            </div>
          )}
          {tooltip && (
            <div
              style={{
                color: '#474C5F99',
                fontWeight: 300,
                fontSize: '12px',
                padding: '4px 8px',
                lineHeight: '1.5',
              }}
            >
              {tooltip}
            </div>
          )}
        </div>
      );

      return (
        <Tooltip
          title={tooltipContent}
          color="#fff"
          styles={{
            body: { cursor: 'pointer', padding: 10, borderRadius: '12px' },
          }}
        >
          <span
            ref={ref}
            onClick={handleClick}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            style={{
              verticalAlign: 'middle',
              boxSizing: 'border-box',
              color: 'rgb(64, 64, 64)',
              cursor: 'pointer',
              flexShrink: 0,
              justifyContent: 'center',
              alignItems: 'center',
              height: '18px',
              marginLeft: '4px',
              fontSize: '12px',
              fontWeight: 400,
              display: 'inline-flex',
              position: 'relative',
              top: '-2px',
              fontVariant: 'tabular-nums',
              background: isHovered && link ? 'rgb(209, 209, 209)' : 'rgb(229, 229, 229)',
              borderRadius: '25px',
              padding: '0px 6px',
              transition: 'all 0.3s ease',
            }}
          >
            {children}
          </span>
        </Tooltip>
      );
    }
    return (
      <span ref={ref} className={className} {...rest}>
        {children}
      </span>
    );
  }),
}); 